package com.ruoyi.web.controller.Utile;

import com.ruoyi.system.domain.vo.UploadResult;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class MinioUtils {
    @Autowired
    private  MinioClient minioClient;
    @Value("${minio.bucketName}")  // 确保已注入
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

//上传至默认桶
    public UploadResult uploadFile(MultipartFile file) throws Exception {
        return uploadFile(file, this.bucketName);
    }


    /**
     * 上传文件到指定存储桶
     * @param file 要上传的文件
     * @param bucketName 存储桶名称
     * @return 文件访问URL
     * @throws Exception 上传过程中可能出现的异常
     */
    public UploadResult uploadFile(MultipartFile file, String bucketName) throws Exception {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        // 获取文件扩展名
        String fileExtension = "";
        int lastDotIndex = originalFilename.lastIndexOf(".");
        if (lastDotIndex > 0) {
            fileExtension = originalFilename.substring(lastDotIndex);
        }

        // 生成唯一文件名
        String newFilename = UUID.randomUUID().toString() + fileExtension;

        try (InputStream inputStream = file.getInputStream()) {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(newFilename)
                            .stream(inputStream, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
        }

        String fileUrl = endpoint + "/" + bucketName + "/" + newFilename;
        return new UploadResult(fileUrl, newFilename, originalFilename);
    }

    //Minio的下载
    public InputStream downloadFile(String objectName) throws Exception {
        return minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
    }
}
